<template>
  <div class="map-container" ref="mapContainer"></div>
  <div class="location-info">
    <p v-if="isLoading" class="loading">定位中... 请稍候...</p>
    <!-- <p v-if="location">经纬度：{{ location.lng }}, {{ location.lat }}</p> -->
    <p v-else-if="errorMsg" class="error">
      {{ errorMsg }}
      <span v-if="errorMsg.includes('INVALID_USER_KEY')">
        <br>请检查高德Key是否正确或已绑定域名
      </span>
      <span v-if="errorMsg.includes('OUT_OF_SERVICE')">
        <br>服务不可用，请检查网络或高德服务状态
      </span>
    </p>
    <!-- <button @click="getLocation" :disabled="isLoading">
      {{ isLoading ? '处理中...' : '重新定位' }}
    </button> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { GET,POST } from "../services/request";
import { showToast } from 'vant';

const mapContainer = ref(null);
let mapInstance = null;
const location = ref(null);
const errorMsg = ref('');
const isLoading = ref(false);
const gdkey = ref('54f2d8a6fbe3fdfee58fce4cd75939f8');

// 高德地图配置（仅保留定位插件）
const AMapConfig = {
  key: gdkey.value, // 保留定位所需的Key
  version: '2.0',
  plugins: ['AMap.Geolocation'] // 移除逆地理编码插件
};

// -------------------------- 核心：定位逻辑 --------------------------
const getLocation = async () => {
  isLoading.value = true;
  errorMsg.value = '';
  location.value = null;

  try {
    if (!AMapConfig.key) {
      throw new Error('请配置有效的高德Key');
    }

    const AMap = await AMapLoader.load(AMapConfig);
    if (!mapContainer.value) throw new Error('地图容器未找到');

    mapInstance = new AMap.Map(mapContainer.value, {
      zoom: 15,
      center: [120.16, 30.25]
    });

    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: false,
      timeout: 15000,
      panToLocation: true
    });
    mapInstance.addControl(geolocation);

    const locationResult = await new Promise((resolve, reject) => {
      geolocation.getCurrentPosition((status, result) => {
        if (status === 'complete') resolve(result);
        else reject(new Error(`定位失败：${result.message || '未知错误'}（${result.code}）`));
      });
    });

    const { position } = locationResult;
    location.value = {
      lng: position.lng.toFixed(6),
      lat: position.lat.toFixed(6)
    };

    console.log('定位成功经纬度:', location.value.lng, location.value.lat);
    getAddress(location.value.lng, location.value.lat);

  } catch (error) {
    if (error.message.includes('INVALID_USER_KEY')) {
      errorMsg.value = '高德Key无效或未绑定域名';
    } else if (error.message.includes('OUT_OF_SERVICE')) {
      errorMsg.value = '高德服务不可用，请稍后重试';
    } else {
      errorMsg.value = error.message || '定位失败，请检查控制台日志';
    }
    console.error('详细错误:', error);
  } finally {
    isLoading.value = false;
  }
};

// 地址逆解析
const getAddress = async (lng, lat) => {
  GET({
    url: `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${gdkey.value}&extensions=all`,
    method: 'get'
  }).then((res) => {
    // console.log(res);
    if (res.status == '1') {
      // console.log(res.regeocode.addressComponent);
      const addressData = JSON.stringify(res.regeocode.addressComponent);
      // console.log(addressData);
      localStorage.setItem('addressData',addressData);
      // localStorage.setItem('flg',1);
      showToast('定位成功')
      // console.log('res', res)
      // this.addmark({ lng, lat, name: res.regeocode.formatted_address })
    } else {
      // this.$message({ message: res.info, type: 'error' })
      // console.log('无法获取定位');
      showToast('请检查网络，当前无法定位')
    }
  })
}

onMounted(() => getLocation());
onUnmounted(() => mapInstance?.destroy());
</script>

<style scoped>
/* 样式不变（移除地址相关样式） */
/* ！！！！！！！！要让地图显示，请给这个.map-container宽高，不给则不显示 */
.map-container {
  width: 100%;
  height: 0px;
  /* border: 1px solid #e5e7eb; */
  /* margin-bottom: 20px; */
}

.location-info {
  padding: 16px;
  font-size: 14px;
}

.loading {
  color: #64748b;
  margin: 0;
}

.error {
  color: #dc2626;
  margin: 0;
}

button {
  margin-top: 10px;
  padding: 8px 16px;
  background: #0066cc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  opacity: 0.9;
}

button:disabled {
  background: #94a3b8;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background: #0052a3;
  opacity: 1;
}
</style>
